#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include "token.h"

#define BUFSIZE 1024
#define BURST 100
#define CPS 10
#define BURST1 1000
#define CPS1 100

int main(int argc, char **argv)
{
	int fd;
	mytbf_t *tbf, *tbf1;

	if (argc < 2)
	{
		fprintf(stderr,"Usage:\n");
		exit(1);
	}
	
	tbf = mytbfInit(CPS, BURST);
	if (tbf < 0)
	{
		fprintf(stdout, "mytbfInit() false!\n");
		exit(1);
	}
	tbf1 = mytbfInit(CPS1, BURST1);
	if (tbf1 < 0)
	{
		fprintf(stdout, "mytbfInit() false!\n");
		exit(1);
	}

	do
	{	
		fd = open(argv[1],O_RDONLY);
		if (fd < 0)
		{
			if (errno != EINTR)
			{
				perror("open()");
				exit(1);
			}
		}
	}while (fd < 0);

	size_t len = 0;
	size_t pos = 0;
	size_t ret = 0;
	int size;
	int count = 0;
	char buf[BUFSIZE];

	while (1)
	{
		if (count > 10)
		{
			size = mytbfFetchToken(tbf1, BUFSIZE);
		}
		else
		{
			size = mytbfFetchToken(tbf, BUFSIZE);
		}
		if (size < 0)
		{
			fprintf(stderr, "mytbfFetchToken():%s\n", strerror(-size));
			exit(1);
		}

		while ((len = read(fd, buf, size)) < 0)
		{
			if (errno == EINTR)
				continue;
			perror("read()");
			break;
		}

		if (len == 0)
			break;
		
		if (size - len > 0)
		{
			if (count > 10)
				mytbfReturnToken(tbf1, size  - len);
			else
				mytbfReturnToken(tbf, size - len);
		}

		pos = 0;
		while (len > 0)
		{
			ret = write(1, buf + pos, len);
			if (ret < 0)
			{
				perror("write()");
				exit(1);
			}
			pos += ret;
			len -= ret;
		}

		struct timespec ts;
		ts.tv_sec = 1;
		ts.tv_nsec = 0;
		nanosleep(&ts, NULL);
		count ++;
	}

	close(fd);

	mytbfDestory(tbf);
	mytbfDestory(tbf1);
    exit(0);
}
